package com.app.service.impl;

import com.app.common.SubsidyApplicationStaticCommon;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.SubsidyApplicationService;
import com.app.util.Result;
import com.app.vo.PageVo;
import com.app.vo.SADetailVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SubsidyApplicationServiceImpl extends ServiceImpl<SubsidyApplicationMapper, SubsidyApplicationModel> implements SubsidyApplicationService {
    @Autowired
    private SubsidyApplicationMapper subsidyApplicationMapper;
    @Autowired
    private SubsidyApplicationDetailsMapper subsidyApplicationDetailsMapper;
    @Autowired
    private PersonalInformationMapper personalInformationMapper;
    @Autowired
    private EnterpriseInformationMapper enterpriseInformationMapper;
    @Autowired
    private ApplicationLogsMapper applicationLogsMapper;

    /**
     * 高校补贴申领状态列表查询
     *
     * @param page
     * @param limit
     * @param user
     * @return
     */
    @Override
    public Result subsidyApplicationList(Integer page, Integer limit, UserModel user) {
        Page<SubsidyApplicationModel> p = new Page<>(page, limit);
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取当前年份
        int currentYear = currentDate.getYear();
        // 获取当前月份
        int currentMonth = currentDate.getMonthValue();


        Page<SubsidyApplicationModel> subsidyApplicationModelPage = subsidyApplicationMapper.selectPage(p, new QueryWrapper<SubsidyApplicationModel>()
                .eq("user_id", user.getId())
                .orderByDesc("crt_time"));
        List<SubsidyApplicationModel> records = subsidyApplicationModelPage.getRecords();
        // 筛选出符合条件的记录(当月数据)
        List<SubsidyApplicationModel> filteredRecords = records.stream()
                .filter(record -> record.getYear() == currentYear && record.getMonth() == currentMonth)
                .collect(Collectors.toList());
        if (filteredRecords.isEmpty()) {//如果当月数据不存在新增
            SubsidyApplicationModel subsidyApplicationModel = new SubsidyApplicationModel();
            subsidyApplicationModel.setYear(currentYear);
            subsidyApplicationModel.setMonth(currentMonth);
            subsidyApplicationModel.setApplicationState(SubsidyApplicationStaticCommon.BRING_APPLICATION);
            subsidyApplicationModel.setUserId(user.getId());
            subsidyApplicationModel.setUserName(user.getUserName());
            subsidyApplicationModel.setCrtTime(LocalDateTime.now());
            this.save(subsidyApplicationModel);
            List<SubsidyApplicationModel> list = new ArrayList<>();
            list.add(subsidyApplicationModel);
            subsidyApplicationModelPage.setRecords(list);
            subsidyApplicationModelPage.setTotal(0);
        }
        //筛选出前几月的且状态为带申领的————》改成已过期
        List<SubsidyApplicationModel> f = subsidyApplicationModelPage.getRecords().stream()
                .filter(record -> record.getYear() != currentYear || record.getMonth() != currentMonth)
                .filter(record -> record.getApplicationState() == SubsidyApplicationStaticCommon.BRING_APPLICATION)
                .map(c -> {
                    c.setApplicationState(SubsidyApplicationStaticCommon.EXPIRED);
                    return c;
                }).collect(Collectors.toList());
        this.updateBatchById(f);//批量修改

        PageVo pageVo = new PageVo();
        pageVo.setCount(subsidyApplicationModelPage.getTotal());
        pageVo.setList(subsidyApplicationModelPage.getRecords());
        return Result.success(pageVo);
    }

    /**
     * 管理后台————大学生就业补贴列表查询（分页、条件）
     *
     * @param page
     * @param limit
     * @param applicationState
     * @param endTimeStr
     * @return
     */
    @Override
    public Result adminList(Integer page, Integer limit, Integer applicationState, String startTime, String endTimeStr) {
        Page<SubsidyApplicationModel> p = new Page<>(page, limit);
        String newEndTimeStr = endTimeStr;
        if(endTimeStr!=null && !"".equals(endTimeStr)){
            // 解析字符串为 LocalDateTime
            LocalDateTime endTime = LocalDateTime.parse(endTimeStr.replace("Z", "+00:00"),
                    DateTimeFormatter.ISO_OFFSET_DATE_TIME);
            // 加一个月
            LocalDateTime newEndTime = endTime.plusMonths(1);
            // 输出新的 endTime
            newEndTimeStr  = newEndTime.atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        }

        Page<SubsidyApplicationModel> subsidyApplicationModelPage = subsidyApplicationMapper.adminList(p,startTime,newEndTimeStr);
//                selectPage(p, new QueryWrapper<SubsidyApplicationModel>()
//                .eq(applicationState != null, "application_state", applicationState)
//                .orderByDesc("crt_time"));
        PageVo pageVo = new PageVo();
        pageVo.setCount(subsidyApplicationModelPage.getTotal());
        pageVo.setList(subsidyApplicationModelPage.getRecords());
        return Result.success(pageVo);
    }

    /**
     * @param subsidyApplicationId
     * @param id
     * @param operator
     * @param processingTime
     * @return
     */
    @Override
    public Result updateListDateStatus(Integer subsidyApplicationId, Integer id, String operator, Date processingTime) {
        SubsidyApplicationDetailsModel subsidyApplicationDetailsModel = subsidyApplicationDetailsMapper.selectOne(new QueryWrapper<SubsidyApplicationDetailsModel>().eq("subsidy_application_id", subsidyApplicationId));
        if (subsidyApplicationDetailsModel != null && subsidyApplicationDetailsModel.getSubsidyState() == SubsidyApplicationStaticCommon.APPROVED) {
            SubsidyApplicationModel subsidyApplicationModel = new SubsidyApplicationModel();
            subsidyApplicationModel.setId(subsidyApplicationId);
            subsidyApplicationModel.setApplicationState(SubsidyApplicationStaticCommon.ISSUED);
            subsidyApplicationModel.setOperator(operator);
            subsidyApplicationModel.setProcessingTime(processingTime);
            subsidyApplicationModel.setUpTime(LocalDateTime.now());
            this.updateById(subsidyApplicationModel);
            //日志表
            ApplicationLogsModel applicationLogsModel = new ApplicationLogsModel();
            applicationLogsModel.setApplicationStatus("已发放");
            applicationLogsModel.setUserId(id);
            applicationLogsModel.setType("补贴申请表状态审核（待发放——>已发放）");
            applicationLogsModel.setCreatTime(LocalDateTime.now());
            applicationLogsModel.setDataId(subsidyApplicationId);
            applicationLogsMapper.insert(applicationLogsModel);
        } else {
            return Result.error(400, "未通过银行审核,禁止修改当前状态");
        }
        return Result.success("更改成功");
    }

    /**
     * 管理后台————根据subsidyApplicationId查详情
     *
     * @param subsidyApplicationId
     * @return
     */
    @Override
    public Result getBySubsidyApplicationId(Integer subsidyApplicationId) {
        SADetailVo saDetailVo = subsidyApplicationDetailsMapper.getBySubsidyApplicationId(subsidyApplicationId);
        return Result.success(saDetailVo);
    }

    /**
     * 管理后台————type 11个人信息通过 12个人信息拒绝 13企业信息通过 14企业信息拒绝
     *
     * @param type
     * @param pOrEId
     * @param reason
     * @param id
     * @param subsidyApplicationDetailId
     * @return
     */
    @Override
    public Result statusPOrE(Integer type, Integer pOrEId, String reason, Integer id, Integer subsidyApplicationDetailId) {
        SubsidyApplicationDetailsModel subsidyApplicationDetailsModel1 = subsidyApplicationDetailsMapper.selectById(subsidyApplicationDetailId);

        SubsidyApplicationDetailsModel subsidyApplicationDetailsModel = new SubsidyApplicationDetailsModel();
        subsidyApplicationDetailsModel.setId(subsidyApplicationDetailId);

        ApplicationLogsModel applicationLogsModel = new ApplicationLogsModel();
        applicationLogsModel.setCreatTime(LocalDateTime.now());
        applicationLogsModel.setUserId(id);
        applicationLogsModel.setDataId(pOrEId);
        if (type == 11 || type == 12) {//个人信息
            applicationLogsModel.setType("个人信息审核");
            PersonalInformationModel personalInformationModel = new PersonalInformationModel();
            personalInformationModel.setId(pOrEId);
            personalInformationModel.setUpTime(LocalDateTime.now());
            if (type == 11) {
                applicationLogsModel.setApplicationStatus("审核通过");
                personalInformationModel.setState(SubsidyApplicationStaticCommon.REVIEW_OF_PERSONNEL_INFORMATION_PASS);
            } else if (type == 12) {
                personalInformationModel.setReason(reason);
                applicationLogsModel.setApplicationStatus("审核未通过");
                applicationLogsModel.setResult(reason);
                personalInformationModel.setState(SubsidyApplicationStaticCommon.REVIEW_OF_PERSONNEL_INFORMATION_FAIL);

                SubsidyApplicationModel subsidyApplicationModel = new SubsidyApplicationModel();
                subsidyApplicationModel.setId(subsidyApplicationDetailsModel1.getSubsidyApplicationId());
                subsidyApplicationModel.setApplicationState(SubsidyApplicationStaticCommon.AWAITING_PARTY);
                subsidyApplicationMapper.updateById(subsidyApplicationModel);

                subsidyApplicationDetailsModel.setSubsidyState(SubsidyApplicationStaticCommon.THE_HUMAN_RESOURCES_AND_SOCIAL_SECURITY_BUREAU_REFUSED_THE_APPLICATION);
                subsidyApplicationDetailsMapper.updateById(subsidyApplicationDetailsModel);
                //日志表（人社局审核）
                ApplicationLogsModel applicationLogsModel1 = new ApplicationLogsModel();
                applicationLogsModel1.setCreatTime(LocalDateTime.now());
                applicationLogsModel1.setUserId(id);
                applicationLogsModel1.setDataId(id);
                applicationLogsModel1.setType("人社局审核");
                applicationLogsModel1.setApplicationStatus("审核未通过（个人信息不合适）");
                applicationLogsMapper.insert(applicationLogsModel1);
            }
            personalInformationMapper.updateById(personalInformationModel);
        } else if (type == 13 || type == 14) {
            applicationLogsModel.setType("企业信息审核");
            EnterpriseInformationModel enterpriseInformationModel = new EnterpriseInformationModel();
            enterpriseInformationModel.setId(pOrEId);
            enterpriseInformationModel.setUpTime(LocalDateTime.now());
            if (type == 13) {
                enterpriseInformationModel.setState(SubsidyApplicationStaticCommon.REVIEW_OF_PERSONNEL_INFORMATION_PASS);
                applicationLogsModel.setApplicationStatus("审核通过");
                //判断个人的是否通过，如果通过，则同步修改补贴申请详情表（tb_subsidy_application_details）的状态为待银行审核
                EnterpriseInformationModel ifPersonSubsidy = subsidyApplicationDetailsMapper.ifPersonSubsidy(pOrEId);
                if (ifPersonSubsidy.getState() == SubsidyApplicationStaticCommon.REVIEW_OF_PERSONNEL_INFORMATION_PASS) {
                    subsidyApplicationDetailsModel.setSubsidyState(SubsidyApplicationStaticCommon.PENDING_BANK_REVIEW);
                    subsidyApplicationDetailsMapper.updateById(subsidyApplicationDetailsModel);
                    //日志表（人社局审核）
                    ApplicationLogsModel applicationLogsModel1 = new ApplicationLogsModel();
                    applicationLogsModel1.setCreatTime(LocalDateTime.now());
                    applicationLogsModel1.setUserId(id);
                    applicationLogsModel1.setDataId(id);
                    applicationLogsModel1.setType("人社局审核");
                    applicationLogsModel1.setApplicationStatus("审核通过");
                    applicationLogsMapper.insert(applicationLogsModel1);
                }
            } else if (type == 14) {
                applicationLogsModel.setApplicationStatus("审核未通过");
                applicationLogsModel.setResult(reason);
                enterpriseInformationModel.setReason(reason);
                enterpriseInformationModel.setState(SubsidyApplicationStaticCommon.REVIEW_OF_PERSONNEL_INFORMATION_FAIL);
                SubsidyApplicationModel subsidyApplicationModel = new SubsidyApplicationModel();
                subsidyApplicationModel.setId(subsidyApplicationDetailsModel1.getSubsidyApplicationId());
                subsidyApplicationModel.setApplicationState(SubsidyApplicationStaticCommon.AWAITING_PARTY);
                subsidyApplicationMapper.updateById(subsidyApplicationModel);

                subsidyApplicationDetailsModel.setSubsidyState(SubsidyApplicationStaticCommon.THE_HUMAN_RESOURCES_AND_SOCIAL_SECURITY_BUREAU_REFUSED_THE_APPLICATION);
                subsidyApplicationDetailsMapper.updateById(subsidyApplicationDetailsModel);
                //日志表（人社局审核）
                ApplicationLogsModel applicationLogsModel1 = new ApplicationLogsModel();
                applicationLogsModel1.setCreatTime(LocalDateTime.now());
                applicationLogsModel1.setUserId(id);
                applicationLogsModel1.setDataId(id);
                applicationLogsModel1.setType("人社局审核");
                applicationLogsModel1.setApplicationStatus("审核未通过（企业信息不合适）");
                applicationLogsMapper.insert(applicationLogsModel1);
            }
            enterpriseInformationMapper.updateById(enterpriseInformationModel);
        }
        applicationLogsMapper.insert(applicationLogsModel);
        return Result.success("审核成功");
    }

    /**
     * 详情的审核接口  type 2待银行审核 3人社局拒绝申请 4银行拒绝申请 5银行审核通过
     *
     * @param subsidyApplicationDetailId
     * @param type
     * @param reason
     * @param id
     * @return
     */
    @Override
    public Result SubsidyApplicationDetailStatus(Integer subsidyApplicationDetailId, Integer type, String reason, Integer id) {
        ApplicationLogsModel applicationLogsModel = new ApplicationLogsModel();
        applicationLogsModel.setCreatTime(LocalDateTime.now());
        applicationLogsModel.setUserId(id);
        applicationLogsModel.setDataId(id);
        SubsidyApplicationDetailsModel subsidyApplicationDetailsModel = new SubsidyApplicationDetailsModel();
        subsidyApplicationDetailsModel.setId(subsidyApplicationDetailId);
        if (type == 5) {
            subsidyApplicationDetailsModel.setSubsidyState(SubsidyApplicationStaticCommon.APPROVED);
            applicationLogsModel.setType("银行审核");
            applicationLogsModel.setApplicationStatus("审核通过");
        } else if (type == 4) {
            subsidyApplicationDetailsModel.setSubsidyState(SubsidyApplicationStaticCommon.THE_BANK_REFUSED_THE_APPLICATION);
            applicationLogsModel.setType("银行审核");
            applicationLogsModel.setApplicationStatus("审核未通过");
            applicationLogsModel.setResult(reason);
            subsidyApplicationDetailsModel.setReason(reason);
        }
        applicationLogsMapper.insert(applicationLogsModel);
        subsidyApplicationDetailsMapper.updateById(subsidyApplicationDetailsModel);
        return Result.success("审核生效");
    }
}
